package com.googlecode.perfectable.visuable.screen;

import java.io.IOException;
import java.io.InputStream;

import com.googlecode.perfectable.eventable.routing.Sink;
import com.googlecode.perfectable.eventable.routing.Source;
import com.googlecode.perfectable.prosperable.message.ClientMessage;
import com.googlecode.perfectable.prosperable.message.ServerMessage;
import com.googlecode.perfectable.visuable.configuration.Configurator;
import com.googlecode.perfectable.visuable.parse.RootFactory;
import com.googlecode.perfectable.visuable.visual.Visual;

public class StandardScreenFactory implements ScreenFactory {

	private final RootFactory rootFactory;
	private final String screenResourceName;

	public StandardScreenFactory(Configurator configurator, String screenResourceName) {
		this.screenResourceName = screenResourceName;
		this.rootFactory = new RootFactory(configurator);
	}

	@SuppressWarnings("static-method")
	protected InputStream loadResources(String resourceName) throws IOException {
		final InputStream resource = Thread.currentThread().getContextClassLoader().getResourceAsStream(resourceName);
		if(resource == null) {
			throw new IOException("Cannot load resource " + resourceName);
		}
		return resource;
	}

	@Override
	public Screen create(Source<ClientMessage> source, Sink<ServerMessage> sink) {
		try(InputStream screenResource = loadResources(this.screenResourceName);) {
			Visual root = this.rootFactory.create(screenResource, source, sink);
			return new StandardScreen(root);
		}
		catch(IOException e) {
			throw new RuntimeException(e); // TODO Auto-generated catch block
		}
	}

}
